package com.foreveross.mofang.datapersistence.infra.utils.impl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.commons.lang.StringUtils;

import com.foreveross.mofang.datapersistence.infra.utils.IFileReadCallback;

/**
 * 文本文件读取回调操作类
 * 
 * @author fb
 */
public abstract class StringFileReadCallback implements IFileReadCallback<String> {
	
	/*
	 *  文件内容读取分隔符，当讲到此处时表示内容是己是一条完整数据，可以进行数据处理了
	 *  如果为空，则默认一行为一条完整数据
	 */
	private String separator;
	
	private StringBuilder data = new StringBuilder();
	
	protected long start = System.currentTimeMillis();
	
	protected long end;
	
	public StringFileReadCallback() {
		
	}
	
	public StringFileReadCallback(String separator) {
		this.separator = separator;
	}
	
	public void setFileInputStream(InputStream input) throws IOException {
		BufferedReader reader = null;
		
		try {
			reader = new BufferedReader(new InputStreamReader(input));
			String line = null;

			while ((line = reader.readLine()) != null) {
				if (StringUtils.isBlank(separator)) {
					execute(line);
					continue;
				}
				
				dataIntegrityCheckout(data, line);
			}
		} finally {
			reader.close();
		}
	}
	
	private void dataIntegrityCheckout(StringBuilder data, String line) {
		String[] datas = line.split(separator);
		
		if (datas.length == 1 && line.indexOf(separator) == -1) {
			data.append(line);
			return;
		}
		
		for (int i = 0; i < datas.length; i++) {
			// 索引第一个肯定己与原来的数据组成了一条完整数据
			if (i == 0) {
				data.append(datas[i]);
				execute(data.toString());
				data.delete(0, data.length());
				continue;
			}
			
			// 同样中间的肯定全是完整数据
			execute(datas[i]);
		}
	}

	public abstract void execute(String data) ;
}
